<template>
  <span class="customer-service-container"></span>
</template>

<script>
  import { isLogin } from '@/utils/auth';

  let init = true;
  let zhiManager = null;
  let openStatus = false;
  let zcElement = null;

  export default {
    name: 'customer-service-container',
    props: {},

    data() {
      return {};
    },

    computed: {
      ...mapGetters(['username', 'nickName', 'userId', 'isLogin']),
      ...mapState({
        route: state => state.route,
        user: state => state.user,
      }),

      currentInfo() {
        return {
          username: this.username,
          nickName: this.nickName,
          userId: this.userId,
          isLogin: this.isLogin,
          routeName: this.route.name,
        };
      },
    },

    watch: {
      currentInfo: {
        handler(info, oldInfo) {
          if (info.userId === oldInfo.userId && isLogin()) return;
          this.resetChatDom();
        },
        deep: true,
      },
    },

    methods: {
      open() {
        //两种打开方式
        //方式一：
        window.open('http://yiweita.com/chat/pc/index.html?sysNum=c7e9a12ad95d4fccb3c8450141ea8e5e',
          'customerService','width=660,height=558,location=0,left=200')
        //方式二：
        // if (!zhiManager) {
        //   this.loadLiveChatApi();
        //   this.loadLiveChatInit();
        // }
        // zhiManager.expand();
        // openStatus = true;
      },
      close() {
        zhiManager.collapse();
        openStatus = false;
      },
      switch() {
        if (openStatus) {
          this.close();
        } else {
          this.open();
        }
      },
      loadLiveChatApi() {
        if (!window.zhiManager && init) {
          init = false;
          // <!-- 自定义咨询按钮:依赖页面存在此节点 -->
          // <button class='ld-customer-btn' style='display: none;'></button>
          const csButton = document.createElement('button');
          csButton.setAttribute('class', 'ld-customer-btn');
          csButton.setAttribute('style', 'display: none;');
          document.body.append(csButton);
          // this.loadLiveChatInit();
        }
      },
      // 初始化聊天组件js
      loadLiveChatInit() {
        zcElement = document.createElement('script');
        zcElement.type = 'text/javascript';
        zcElement.async = true;
        zcElement.setAttribute('class', 'ld-customer-btn'); // 与创建的按钮class保持一致
        zcElement.setAttribute('id', 'zhichiScript');
        zcElement.setAttribute('data-args', 'manual=true');
        zcElement.src = `${
          document.location.protocol === 'https:' ? 'https://' : 'http://'
          }yiweita.com/frame/js/entrance.js?sysNum=c7e9a12ad95d4fccb3c8450141ea8e5e`;
        if (zcElement.addEventListener) {
          zcElement.addEventListener('load', this.chatApiLoaded);
          zcElement.addEventListener('error', this.chatNotLoaded);
        }
        if (zcElement.attachEvent) {
          zcElement.attachEvent('load', this.chatApiLoaded);
        }
        document.body.append(zcElement);
      },
      chatNotLoaded() {
        // console.log('客服聊天加载失败！');
      },
      // js加载完毕执行数据初始化
      chatApiLoaded() {
        // 初始化智齿咨询组件实例，
        // 段落关闭/* eslint-disable */，单行关闭 // eslint-disable-line 或// eslint-disable-next-line，文件关闭/* eslint-enable */
        /* eslint-disable */
        zhiManager = getzhiSDKInstance(); // eslint-disable-line
        // 再调用load方法
        zhiManager.on('load', () => {
          zhiManager.initBtnDOM();
        });
        zhiManager.set('color', '1a1c2a'); //设置颜色
        zhiManager.set('title', '欢迎咨询');
        // zhiManager.set('horizontal', 50); //设置水平边距，默认水平为 20 像素
        // zhiManager.set('vertical', 50); //设置垂直边距，默认垂直为 40 像素
        zhiManager.set('size', { width: 400, height: 540 }); //设置聊天页窗口大小
        zhiManager.set('powered', false); //隐藏聊天窗体底部的智齿科技冠名
        // zhiManager.set('customBtn', 'true'); //完成自定义按钮设置
        zhiManager.set('customBtn', 'true'); //完成自定义按钮设置
        zhiManager.set('lan', 'cn'); //支持语言（cn，en）
        zhiManager.set('moduleType', 3);
        zhiManager.set('manTrace', true);
        zhiManager.set('isInviteFlag', 'false');
        zhiManager.set('tipTitle', '贝博客服邀请您进入会话');
        zhiManager.set('overTimeout', 30);
        this.updateUserInfo();
        // console.log('设置成功！')
        // setTimeout(this.loadCustomService, 3000);
      },
      // 传入用户信息
      updateUserInfo() {
        const userInfo = this.user;
        if (userInfo && zhiManager) {
          zhiManager.set('userinfo', {
            tel: userInfo.telArea + userInfo.telephone, //电话或手机
            email: userInfo.email, //邮箱
            uname: userInfo.nickName || userInfo.username || '会员PC访客', //昵称
            visitTitle: this.route.name, //对话页标题，若不传入系统将获取用户打开咨询组件时所在页面的标题
            visitUrl: this.route.path, //对话页URL，若不传入系统将获取用户打开咨询组件时所在页面的URL
            face: '', //头像URL
            realname: userInfo.reallyName, //真实姓名
            weibo: '', //微博账号
            weixin: '', //微信账号
            qq: '', //QQ号
            sex: userInfo.sex === 1 ? 0 : 1, //0 男 1 女
            birthday: userInfo.birthday, //生日，如“1990-01-01”
            remark: userInfo.remark, //用户的备注信息
            params: '{"层级":"" + userInfo.levelName}' //自定义用户信息字段
          });
          // 强制设置一下用户名
          zhiManager.set(
            'uname',
            userInfo.nickName || userInfo.username || '会员PC访客'
          );
          zhiManager.set('partnerId', userInfo.id || moment.now());
        }
      },
      // 删除节点重新加载js文件
      resetChatDom() {
        const deleteArr = [
          document.getElementById('zhichiScript'),
          document.getElementById('zhichiBtnBox'),
          document.getElementById('ZCChatFrame'),
        ];
        deleteArr.forEach(item => {
          item && document.getElementsByTagName('body')[0].removeChild(item);
        });
        this.loadLiveChatInit();
      },
    },

    mounted() {
      this.loadLiveChatApi();
      this.$global.bus.$on('open', this.switch);
    }
  };
</script>

<style lang='scss' scoped>
  .customer-service-container {
    position: relative;
  }
</style>
